import {Action, commit} from '@/store/Utils';
import {store} from '@/store/Store';
import {postAccessToken, postAccessToken2} from '@/base/api/AuthApi';
import Cookies from 'js-cookie';
import {settings} from '@/config/Settings';
import {deepAssign} from '@/base/util/Objects';

const {title, cookieExpires} = settings;
const TOKEN_KEY = 'accessToken';
const TYP = 'userType';

const setToken = (token: string) => {
  Cookies.set(TOKEN_KEY, token, {expires: cookieExpires || 1});
};

const setType = (from: string) => {
  Cookies.set(TYP, from, {expires: cookieExpires || 1});
};

const getToken = () => {
  const token = Cookies.get(TOKEN_KEY);
  return token || false;
};
const getType = () => {
  const userType = Cookies.get(TYP);
  return userType || false;
};
export class AuthState {
  accessToken = getToken() ? getToken().toString() : ''
  userType = getType() ? getType().toString() : ''
  recoverSnapshot() {
    this.accessToken = getToken() ? getToken().toString() : ''
    this.userType = getType() ? getType().toString() : ''
    return this;
  }

  saveSnapshot() {
    return this;
  }
}

abstract class BaseAction implements Action {
  namespace? = 'auth';
}

class SetAction extends BaseAction {
  accessToken?: string;
  userType?: string;
  static typed(state: AuthState, payload: SetAction): void {
    deepAssign(state, payload);
  }
}

export const auth = {
  namespaced: true,
  state: new AuthState().recoverSnapshot(),
  getters: {},
  actions: {},
  mutations: {
    [SetAction.name]: SetAction.typed
  }
};

export class authBloc {
  static get state() {
    return store.state.auth;
  };

  static reset() {
    commit(SetAction, new AuthState());
  }

  static login(email: string, password: string, from: any) {
    return postAccessToken(email, password, 'client-id').then(res => {
      const accessToken = res.data.accessToken;
      const userType = from;
      setToken(accessToken);
      setType(userType);
      commit(SetAction, {accessToken, userType});
      return res;
    });
  }
  static login2(email: string, password: string, from: any) {
    return postAccessToken2(email, password, 'client-id').then(res => {
      const accessToken = res.data.accessToken;
      const userType = from;
      setToken(accessToken);
      setType(userType);
      commit(SetAction, {accessToken, userType});
      return res;
    });
  }

  static logout() {
    setToken('');
    setType('');
    commit(SetAction, {accessToken: '', userType: ''});
  }
}
